<template>
  <!-- 采购第二步 -->
  <div class="step2 mt-2">
    <div class="top">
      <div class="flexcc left">
        <div class="bold">
          <span>{{ t(`procurement.step2`) }}:</span>
          <span v-if="locale === 'zh-CN'">编辑【{{ store.category.projectName }}】采购单</span>
          <span v-if="locale === 'en'">Edit [{{ store.category.projectName }} ] purchase order</span>
        </div>
        <el-button
          type="primary"
          class="ml-2"
          @click="handleAssociatedShip"
        >
          {{ t(`procurement.btn2`) }}
        </el-button>
      </div>
      <div class="right">
        <el-button
          type="primary"
          @click="handleBack"
        >
          {{ t(`procurement.Back`) }}
        </el-button>
        <el-button
          type="primary"
          @click="handleNext"
        >
          {{ t(`procurement.NextStep`) }}
        </el-button>
        <el-button
          type="primary"
          color="#252628"
          @click="handleSave('save')"
        >
          {{ t(`procurement.Save`) }}
        </el-button>
      </div>
    </div>

    <ShippingInfo
      v-if="shippingInfo"
      :data="shippingInfo"
    />

    <div
      class="module mt-2"
      v-if="!shippingInfo && !detailInfo?.shipRepairYardName && !detailInfo?.repairYardCountries && !detailInfo?.repairYardArea"
    >
      {{ t('procurement.step2page.text1') }}
    </div>

    <el-form
      ref="formEl"
      class="mt-3"
      :model="formData"
      :rules="rules"
      label-width="180px"
      label-position="top"
      status-icon
      hide-required-asterisk
    >
      <!-- 采购声明 -->
      <div class="module">
        <div class="title">{{ t('procurement.step2page.form.l1') }}</div>
        <el-form-item
          prop="procureStatement"
          class="mt-2"
        >
          <el-input
            v-model="formData.procureStatement"
            type="textarea"
            :placeholder="t('procurement.step2page.form.p1')"
            maxlength="300"
            show-word-limit
          />
        </el-form-item>
      </div>

      <div class="module mt-3">
        <div class="title">{{ t('dockRepair.label3') }}</div>
        <el-form-item
          prop="quoteOrderCurrency"
          class="mt-2"
        >
          <el-select
            v-model="formData.quoteOrderCurrency"
            class="wp-100"
            :placeholder="t('select_p')"
            filterable
            clearable
          >
            <el-option
              v-for="item in dictData['currency']"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            />
          </el-select>
        </el-form-item>
      </div>


      <div class="module mt-3">
        <div class="title">{{ t('procurement.step2page.form.l2') }}</div>
        <el-form-item class="mt-2">
          <el-cascader
              ref="cascaderRef"
              v-model="category"
              class="wp-100"
              filterable
              clearable
              :options="threeLevelOptions"
              :props="{ value: 'purchasingProjectId', label: 'projectName', children: 'purchasingProjectWebVoList' }"
              @change="handleChange"
          />
        </el-form-item>
      </div>
    </el-form>

    <div class="list mt-2">
      <!-- <div class="group flexsc"> -->
      <!-- <div class="mr-4" v-if="locale === 'zh-CN'">已选 1 项</div>
        <div class="mr-4" v-if="locale === 'en'">1 item selected</div> -->

      <!-- 采购项目 -->
      <!-- <el-button
          type="primary"
          @click="handleAdd"
        >
          +{{ t(`procurement.btn1`) }}
        </el-button>
      </div> -->

      <div class="table mt-2">
        <el-auto-resizer>
          <template #default="{ height, width }">
            <el-table-v2
              :columns="columns"
              :data="tableData"
              :width="width"
              :height="height"
              :header-align="'center'"
              fixed
            >
              <template #empty>
                <div class="flexcc-col mt-4">
                  <div>
                    <img
                      src="@/assets/img/icon_wushuju.png"
                      alt=""
                    />
                  </div>
                  <div class="mt-2">
                    {{ t('procurement.noDataText') }}
                  </div>
                  <el-button
                    type="primary"
                    @click="handleAddOne(0)"
                    class="mt-2"
                  >
                    +{{ t(`procurement.btn1`) }}
                  </el-button>
                </div>
              </template>
            </el-table-v2>
          </template>
        </el-auto-resizer>
      </div>
    </div>

    <div class="file-list mt-5">
      <Uploads
        ref="UploadsRef"
        @change="fileChange"
        :tip="t('Uploads.t2')"
      />
    </div>

    <!-- 设备项目录入 -->
    <ProjectAdd
      v-if="dialogProjectAdd"
      :visible="dialogProjectAdd"
      :editRow="editRow"
      :checkedRow="checkedRow"
      @close="dialogProjectAdd = false"
      @getDetail="getDetail(false)"
    />

    <!-- 关联船舶 -->
    <AssociatedShip
      v-if="dialogAssociatedShip"
      :visible="dialogAssociatedShip"
      :shippingId="shippingId"
      :enterpriseInfo="enterpriseInfo"
      @getDetail="getDetail(false)"
      @close="dialogAssociatedShip = false"
    />

    <!-- 保存确认 -->
    <Confirm
      v-if="dialogConfirmSave"
      :visible="dialogConfirmSave"
      :title="t('procurement.step2page.Confirm.title')"
      :text="t('procurement.step2page.Confirm.text')"
      :cancelText="t('donNotSaveText')"
      @cancel="handleDelete"
      @close="dialogConfirmSave = false"
      @confirm=";(dialogConfirmSave = false), handleSave('back')"
    />

    <!-- 保存后设置可查看人员 -->
    <ConfigPerson
      v-if="dialogConfigPerson"
      :visible="dialogConfigPerson"
      :saveType="saveType"
      :canViewPerson="canViewPerson"
      @close="dialogConfigPersonClose"
    />
  </div>
</template>

<script setup lang="jsx">
import { ref, unref, watch, computed, onBeforeMount, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useI18n } from 'vue-i18n'
import useProcurement from '@/stores/procurement.js'
import useLogin from '@/stores/login.js'
import { detailApi, deleteApi, deleteDetailApi, editApi, editOrderDetailApi, batchUpdateTypeApi } from '@/service/procurement'
import { uploads } from '@/service/common.js'
import { debounce } from 'lodash'

import AssociatedShip from './AssociatedShip.vue' // 关联船舶
import Confirm from '@/components/Confirm.vue' // 确认框
import ConfigPerson from './ConfigPerson.vue' // 设置可查看人员

import ProjectAdd from './ProjectAdd.vue' // 项目录入
import Uploads from '@/components/Uploads.vue'

import useDict from '@/hooks/useDict'
const { dictData, getDictData, getDictLabel } = useDict()
const storeLogin = useLogin()

const router = useRouter()
const route = useRoute()

const { t, locale } = useI18n()

onMounted(() => {
  init()
})
watch(locale, (n) => {
  init()
})

const store = useProcurement()
const { next, back, setOrderInfo, setSecondLevel } = store

const category = ref([])
// 二级类别
const secondLevelOptions = computed(() => {
  return store.category.purchasingProjectWebVoList
})

// 三级类别
const threeLevelOptions = computed(() => {
  return secondLevelOptions.value.find((item) => item.purchasingProjectId === store.secondLevel?.purchasingProjectId)?.purchasingProjectWebVoList || []
})

const cascaderRef = ref() // 级联ref
const projectName = ref('') // 三级（备件名称）
const handleChange = (val) => {
  projectName.value = cascaderRef.value.getCheckedNodes()[0].label
  batchUpdateTypeApi({
    orderId: store.orderInfo.id,
    projectId: val[val.length - 1]
  }).then(() => {
    getDetail(false)
  })
}

// 返回时
const handleBack = () => {
  dialogConfirmSave.value = true
}

// 保存确认
const dialogConfirmSave = ref(false)

// 删除采购单
const handleDelete = () => {
  deleteApi(store.orderInfo.id).then(({ msg }) => {
    dialogConfirmSave.value = false
    back()
    router.replace({
      path: route.path
    })
  })
}

// 保存后设置可查看人员
const dialogConfigPerson = ref(false)
const canViewPerson = ref([])
const dialogConfigPersonClose = () => {
  dialogConfigPerson.value = false
  if (saveType.value === 'save') {
    getDetail()
  }
}

// 下一步
const handleNext = () => {
  handleSave('next')
}

// 保存
const saveType = ref('save') // save保存  next下一步 back上一步
const handleSave = (type = 'save') => {
  if (!formEl.value) return

  const { procureOrderName, _procureOrderName } = store.orderInfo

  const params = {
    ...detailInfo.value,
    ...formData.value
  }

  if (!_procureOrderName) {
    ElMessage.warning(t('procurement.step2page.w1'))
    return
  }
  params.procureOrderName = _procureOrderName

  formEl.value.validate(async (valid, fields) => {
    if (valid) {
      params.urlList = await handleUpload()

      editApi(params).then(() => {
        dialogConfigPerson.value = true
        saveType.value = type
        getDetail()
      })
    }
  })
}

// 关联船舶
const dialogAssociatedShip = ref(false)
const handleAssociatedShip = () => {
  dialogAssociatedShip.value = true
}

// 表单
const formEl = ref(null)
const formData = ref({})
const rules = reactive({
  procureStatement: [{ required: true, message: t('procurement.step2page.r1'), trigger: 'blur' }],
  quoteOrderCurrency: [{ required: true, message: t('dockRepair.step2page.r5'), trigger: 'change' }]
})

// 项目录入
const dialogProjectAdd = ref(false)
watch(dialogProjectAdd, (n) => {
  if (!n) {
    editRow.value = null
  }
})

// 复选框 组件
const SelectionCell = ({ value, intermediate = false, onChange }) => {
  return (
    <ElCheckbox
      onChange={onChange}
      modelValue={value}
      indeterminate={intermediate}
    />
  )
}

// 正在编辑的行
const editRow = ref(null)

// 勾选的 行
const checkedRow = ref(null)

// 获取列
const columns = ref([])
const getColumns = () => {
  const setRef = (el) => {
    if (el) {
      el.focus?.()
    }
  }
  const setEditingClassName = (flag = true) => {
    return { 'table-v2-inline-editing-trigger': flag }
  }

  // 保存
  const handleRowSave = debounce(
    (rowData) => {
      editOrderDetailApi(rowData).then(({ msg, data }) => {
        ElMessage.success(msg)
        rowData.isSave = true
        rowData.editingKey = null
        rowData.id = data
      })
    },
    500,
    {
      leading: true, // 延长开始后调用
      trailing: false // 延长结束前调用
    }
  )

  // 回车保存
  const handleEnterSave = (e, rowData) => {
    if (['Enter', 'NumpadEnter'].includes(e.code)) {
      handleRowSave(rowData)
    }
  }

  columns.value = [
    // {
    //   key: 'selection',
    //   width: 50,
    //   fixed: 'left',
    //   align: 'center',
    //   cellRenderer: ({ rowData }) => {
    //     const _data = unref(tableData.value)
    //     const onChange = (value) => {
    //       _data.forEach((row) => (row.checked = false))
    //       rowData.checked = value
    //       checkedRow.value = value ? rowData : null
    //     }

    //     return (
    //       <SelectionCell
    //         value={rowData.checked}
    //         onChange={onChange}
    //       />
    //     )
    //   }
    // },
    {
      title: t('indexNumber'),
      key: 'index',
      dataKey: 'index',
      width: 50,
      cellRenderer: ({ rowIndex }) => {
        return rowIndex + 1
      }
    },
    {
      title: t('procurement.ProjectAdd.l2_1'),
      key: 'procureName',
      dataKey: 'procureName',
      width: 200,
      cellRenderer: ({ rowData }) => {
        if (rowData.editingKey === 'procureName') {
          return (
            <el-input
              ref={setRef}
              v-model={rowData.procureName}
              placeholder={t('procurement.ProjectAdd.l2_2')}
              maxlength={50}
              onBlur={() => {
                handleRowSave(rowData)
              }}
              onKeyup={(e) => handleEnterSave(e, rowData)}
            />
          )
        }

        const onEnterEditMode = () => {
          rowData.editingKey = 'procureName'
        }

        return (
          <div
            class={setEditingClassName()}
            onClick={onEnterEditMode}
          >
            {rowData.procureName}
          </div>
        )
      }
    },
    {
      title: t('procurement.ProjectAdd.l3_1'),
      key: 'procureNo',
      dataKey: 'procureNo',
      width: 210,
      cellRenderer: ({ rowData }) => {
        if (rowData.editingKey === 'procureNo') {
          return (
            <el-input
              ref={setRef}
              v-model={rowData.procureNo}
              placeholder={t('procurement.ProjectAdd.p3_1')}
              maxlength={50}
              onBlur={() => {
                handleRowSave(rowData)
              }}
              onKeyup={(e) => handleEnterSave(e, rowData)}
            />
          )
        }

        const onEnterEditMode = () => {
          rowData.editingKey = 'procureNo'
        }

        return (
          <div
            class={setEditingClassName()}
            onClick={onEnterEditMode}
          >
            {rowData.procureNo}
          </div>
        )
      }
    },
    {
      title: t('procurement.ProjectAdd.l11'),
      key: 'drawingNumber',
      dataKey: 'drawingNumber',
      width: 150,
      cellRenderer: ({ rowData }) => {
        if (rowData.editingKey === 'drawingNumber') {
          return (
            <el-input
              ref={setRef}
              v-model={rowData.drawingNumber}
              placeholder={t('procurement.ProjectAdd.p3_1')}
              maxlength={50}
              onBlur={() => {
                handleRowSave(rowData)
              }}
              onKeyup={(e) => handleEnterSave(e, rowData)}
            />
          )
        }

        const onEnterEditMode = () => {
          rowData.editingKey = 'drawingNumber'
        }

        return (
          <div
            class={setEditingClassName()}
            onClick={onEnterEditMode}
          >
            {rowData.drawingNumber}
          </div>
        )
      }
    },
    {
      title: t('procurement.ProjectAdd.l4'),
      key: 'procureSpec',
      dataKey: 'procureSpec',
      width: 100,
      cellRenderer: ({ rowData }) => {
        if (rowData.editingKey === 'procureSpec') {
          return (
            <el-input
              ref={setRef}
              v-model={rowData.procureSpec}
              placeholder={t('procurement.ProjectAdd.p4-3')}
              maxlength={50}
              onBlur={() => {
                handleRowSave(rowData)
              }}
              onKeyup={(e) => handleEnterSave(e, rowData)}
            />
          )
        }

        const onEnterEditMode = () => {
          rowData.editingKey = 'procureSpec'
        }

        return (
          <div
            class={setEditingClassName()}
            onClick={onEnterEditMode}
          >
            {rowData.procureSpec}
          </div>
        )
      }
    },
    // {
    //   title: t('procurement.col.t2'),
    //   key: 'procureModel',
    //   dataKey: 'procureModel',
    //   width: 100,
    //   cellRenderer: ({ rowData }) => {
    //     if (!rowData.isSave) {
    //       return (
    //         <el-input
    //           v-model={rowData.procureModel}
    //           placeholder={t('procurement.ProjectAdd.p4-2')}
    //           maxlength={50}
    //         />
    //       )
    //     }
    //     return rowData.procureModel
    //   }
    // },
    {
      title: t('procurement.col.t3'),
      key: 'unit',
      dataKey: 'unit',
      width: 100,
      cellRenderer: ({ rowData }) => {
        if (rowData.editingKey === 'unit') {
          return (
            <el-input
              ref={setRef}
              v-model={rowData.unit}
              placeholder={t('procurement.ProjectAdd.p7-2')}
              maxlength={50}
              onBlur={() => {
                handleRowSave(rowData)
              }}
              onKeyup={(e) => handleEnterSave(e, rowData)}
            />
          )
        }

        const onEnterEditMode = () => {
          rowData.editingKey = 'unit'
        }

        return (
          <div
            class={setEditingClassName()}
            onClick={onEnterEditMode}
          >
            {rowData.unit}
          </div>
        )
      }
    },
    {
      title: t('procurement.category4Col.tit5'),
      key: 'requireCount',
      dataKey: 'requireCount',
      width: 100,
      cellRenderer: ({ rowData }) => {
        if (rowData.editingKey === 'requireCount') {
          return (
            <el-input-number
              ref={setRef}
              v-model={rowData.requireCount}
              placeholder={t('procurement.ProjectAdd.p10')}
              controls={false}
              style="width: 100%"
              max={999999999}
              onBlur={() => {
                handleRowSave(rowData)
              }}
              onKeyup={(e) => handleEnterSave(e, rowData)}
            />
          )
        }

        const onEnterEditMode = () => {
          rowData.editingKey = 'requireCount'
        }

        return (
          <div
            class={setEditingClassName()}
            onClick={onEnterEditMode}
          >
            {rowData.requireCount}
          </div>
        )
      }
    },
    {
      title: t('procurement.category2Col.tit8'),
      key: 'remark',
      dataKey: 'remark',
      width: 200,
      cellRenderer: ({ rowData }) => {
        if (rowData.editingKey === 'remark') {
          return (
            <el-input
              ref={setRef}
              v-model={rowData.remark}
              placeholder={t('procurement.ProjectAdd.p8')}
              maxlength={100}
              onBlur={() => {
                handleRowSave(rowData)
              }}
              onKeyup={(e) => handleEnterSave(e, rowData)}
            />
          )
        }

        const onEnterEditMode = () => {
          rowData.editingKey = 'remark'
        }

        return (
          <div
            class={setEditingClassName()}
            onClick={onEnterEditMode}
          >
            {rowData.remark}
          </div>
        )
      }
    },
    {
      title: t('procurement.operation'), // 操作
      width: 100,
      fixed: 'right',
      cellRenderer: ({ rowData, rowIndex }) => {
        const _data = unref(tableData.value)

        // 删除
        const handleDelete = (value) => {
          if (!rowData.id) {
            _data.splice(rowIndex, 1)
            return
          }
          deleteDetailApi({
            id: rowData.id
          }).then(({ msg }) => {
            ElMessage.success(msg)
            _data.splice(rowIndex, 1)
          })
        }
        return (
          <>
            <el-popconfirm
              title={t('popconfirm_del')}
              v-slots={{
                reference: () => (
                  <img
                    src={new URL('@/assets/img/icon_shanchu.png', import.meta.url)}
                    height="22"
                    class="mr-2"
                  />
                )
              }}
              onConfirm={handleDelete}
            ></el-popconfirm>

            <el-icon onClick={() => handleAddOne(rowIndex)}>
              <Plus />
            </el-icon>
          </>
        )
      }
    }
  ]
}
// 表格数据
const tableData = ref([])

// 详情
const shippingInfo = ref(null) // 船舶信息
const shippingId = ref(null) // 船舶id
const enterpriseInfo = ref(null) // 修船厂信息
const detailInfo = ref(null)
const getDetail = (isUpdate = true) => {
  detailApi(store.orderInfo.id).then(({ data }) => {
    detailInfo.value = data
    data._procureOrderName = data.procureOrderName

    const { shcwShippingVo, shippingId: sid, procureStatement, quoteOrderCurrency, shipRepairYardName, repairYardCountries, repairYardArea, procureOrderDetailEditVoList, canViewPerson: person, urlList } = data

    if (shcwShippingVo) {
      shippingInfo.value = shcwShippingVo
    }
    if (procureOrderDetailEditVoList?.length) {
      const { mediumId, purchasingProjectId } = procureOrderDetailEditVoList[0]
      setSecondLevel({ purchasingProjectId: mediumId })
      category.value = [purchasingProjectId]
      procureOrderDetailEditVoList.forEach((item) => {
        item.isSave = true
      })
      tableData.value = procureOrderDetailEditVoList
    }
    shippingId.value = sid
    enterpriseInfo.value = {
      enterpriseName: shipRepairYardName,
      enterpriseCountry: repairYardCountries,
      enterpriseAre: repairYardArea
    }

    let qc = ''
    if (['中国', 'China'].includes(storeLogin.userInfo.enterpriseCountry)) {
      qc = 'currency_0'
    } else {
      qc = 'currency_1'
    }

    if (isUpdate) {
      formData.value = {
        procureStatement,
        quoteOrderCurrency: quoteOrderCurrency || qc
      }
      setOrderInfo(data)
    }

    if (person) canViewPerson.value = person

    if (urlList) {
      fileList.value = urlList.map((item) => {
        return {
          name: item.slice(item.lastIndexOf('/') + 1),
          url: item
        }
      })
    }

    UploadsRef.value.setFileList(fileList.value)
  })
}

// 添加采购项目
const handleAdd = () => {
  dialogProjectAdd.value = true
}

// 加一行
const handleAddOne = (index) => {
  // if (!category.value.length) {
  //   ElMessage.warning(t('procurement.step2page.form.r2'))
  //   return
  // }
  tableData.value.splice(index + 1, 0, {
    projectName: projectName.value || cascaderRef.value?.getCheckedNodes()[0]?.label,
    procureOrderId: store.orderInfo.id,
    largeId: store.category.purchasingProjectId,
    mediumId: store.secondLevel.purchasingProjectId,
    purchasingProjectId: category.value[category.value.length - 1]
  })

  // console.log(tableData.value, '==')
}

// 文件列表
const fileList = ref([])
const fileChange = (val) => {
  fileList.value = val
}
const UploadsRef = ref(null)
const handleUpload = () => {
  return new Promise((resolve, reject) => {
    const newList = fileList.value.filter((item) => item.raw)
    const oldList = fileList.value.filter((item) => !item.raw).map((item) => item.url)

    if (newList.length) {
      const formData = new FormData()
      newList.forEach((item) => {
        formData.append('files', item.raw)
      })
      uploads(formData).then(({ urls }) => {
        const resultFile = urls.split(',')
        fileList.value = resultFile.map((item) => {
          return {
            name: item.slice(item.lastIndexOf('/') + 1),
            url: item
          }
        })
        UploadsRef.value.setFileList(fileList.value)
        resolve([...oldList, ...resultFile])
      })
    } else {
      resolve(oldList)
    }
  })
}

// init
const init = async () => {
  getDictData('currency')
  getDictData('ships_type')
  getDictData('classification_society')
  getColumns()
  getDetail()
}
</script>

<style scoped lang="scss">
.step2 {
  .filter {
    background: #fff;
    padding: 24px 114px;
    display: grid;
    grid-template-columns: repeat(2, 500px);
    grid-template-rows: repeat(2, 38px);
    row-gap: 20px;
    column-gap: 30px;
  }
  padding-bottom: 36px;
  .el-button {
    min-width: 150px;
  }
  .top {
    display: grid;
    grid-template-columns: repeat(2, auto);
    gap: 0px;
    justify-content: space-between;
  }

  .grid {
    display: grid;
    grid-template-columns: repeat(3, 370px) 105px;
    gap: 15px;
  }

  .module {
    background: #fff;
    padding: 24px;
    .title {
      border-bottom: #252628 2px solid;
      color: #252628;
      padding-bottom: 10px;
    }
  }

  .list {
    background: #fff;
    padding: 24px 24px 0;

    .table {
      border-top: 2px solid #252628;
      height: 700px;

      :deep(.table-v2-inline-editing-trigger) {
        border: 1px transparent dotted;
        padding: 4px;
        min-height: 26px;
        min-width: 100%;
        cursor: text;
        border-radius: 3px;
      }

      :deep(.table-v2-inline-editing-trigger:hover) {
        border-color: var(--el-color-primary);
      }

      :deep(.el-table-v2__header-cell) {
        background: #f0f3f8;
        color: #252628;
        justify-content: center;
      }
    }
  }
}
</style>
